// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class IronBridge extends cc.Component {

    @property(cc.Node)
    left: cc.Node = null;
    @property(cc.Node)
    right: cc.Node = null;
    @property(cc.Node)
    centre: cc.Node = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {}

    start () {
        this.init(this.right);
        this.init2(this.left);
    }

    init(node){
        for(let i = 0; i < node.children.length; i++) {
            let targetNode = node.children[i - 1];
            if (i == 0) {
                targetNode = this.centre;
            }
            let joint = node.children[i].addComponent(cc.RevoluteJoint);
            joint.connectedBody = targetNode.getComponent(cc.RigidBody);
            joint.connectedAnchor = cc.v2((targetNode.width + node.children[i].width)/2 - 10, 0);
            joint.apply();
        }
    }

    init2(node){
        for(let i = node.children.length -1; i >= 0; i--) {
            let targetNode = node.children[i + 1];
            if (i ==  node.children.length -1) {
                targetNode = this.centre;
            }
            let joint = node.children[i].addComponent(cc.RevoluteJoint);
            joint.connectedBody = targetNode.getComponent(cc.RigidBody);
            joint.connectedAnchor = cc.v2(-(targetNode.width + node.children[i].width)/2 + 10, 0);
            joint.apply();
        }
    }

    // update (dt) {}
}
